const cache = require('memory-cache');

/**
 *
 * @param key
 * @param data
 * @param duration 默认缓存3小时
 * @return {Promise<unknown>}
 */
function setCache(key, data, duration = 60000*60*3) {
    // return new Promise((resolve, reject) => {
        cache.put(key, data, duration, (key, value) => {
            if (value) {
                console.log('缓存设置成功')
            }
        });
    // });
}

// 获取缓存数据
function getCache(key) {
    return new Promise((resolve, reject) => {
        const data = cache.get(key);
        if (data) {
            console.log(`Cache  found for key: ${key}`)
            resolve(data);
        } else {
            console.log(`Cache not found for key: ${key}`)
            resolve(false)
        }
    });
}

// 判断缓存数据是否过期
function isCacheExpired(key) {
    return new Promise((resolve) => {
        const data = cache.get(key);
        resolve(!data);
    });
}

module.exports = {
    setCache,
    getCache,
    isCacheExpired,
};
